/**
 * 
 */
package cn.edu.ujn.common.elasticSearch;

import java.io.IOException;
import java.lang.reflect.Field;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

/**
 * @author 曹仁道 
 * @方法描述：
 */
public class JsonUtil {
	/**
	 * 实现将实体对象转换成json对象
	 * @param <T>
	 * 
	 * @param medicine
	 *            Medicine对象
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String obj2JsonData(Object obj) {
		String jsonData = null;
		try {
			// 使用XContentBuilder创建json数据
			Class<Object> class_t=(Class<Object>) obj.getClass();
			class_t.newInstance();
			Field[] fields=class_t.getDeclaredFields();
			
			XContentBuilder jsonBuild = XContentFactory.jsonBuilder();
			for(int i=0;i<fields.length;i++){
				Field field=fields[i];
				field.setAccessible(true);
				if(i==0){
					jsonBuild.startObject().field(field.getName(),field.get(obj));
				}else if(i==(fields.length-1)){
					jsonBuild.field(field.getName(),field.get(obj)).endObject();
				}else{
					jsonBuild.field(field.getName(),field.get(obj));
				}
				
			}
			/*jsonBuild.startObject().field("id", medicine.getId()).field("name", medicine.getName())
					.field("funciton", medicine.getFunction()).endObject();*/
			jsonData = jsonBuild.string();
			System.out.println(jsonData);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonData;
	}
}
